const replyVia = require('../wrapReply');
const rpc = require('../rpc');

function plugin(options = { serviceUuid: 'unset' }) {
    let { serviceUuid } = options;
    this.add(`role:discovery-receive,cmd:add`, (msg, reply) => {
        let { uuid, config } = msg;
        if(uuid == serviceUuid) {
            console.log('receive boardcast to notify self added, ignore');
            reply();
            return;
        }
        console.log(`adding ${uuid} to rpc-clients`);
        replyVia(async () => {
            await rpc.actAsync({ role: 'transport', type: 'balance', add: 'client', config });
            console.log(`${uuid} has been add to rpc-clients`);
            return { msg: `endpoint added from rpc...${JSON.stringify(config)}` }
        }, reply);
    });
    this.add(`role:discovery-receive,cmd:remove`, (msg, reply) => {
        let { uuid, config } = msg;
        if(uuid == serviceUuid) {
            console.warn('receive boardcast to notify self removed, ignore');
            reply();
            return;
        }
        console.log(`removing ${uuid} from rpc-clients`);
        replyVia(async () => {
            await rpc.actAsync({ role: 'transport', type: 'balance', remove: 'client', config });
            console.log(`${uuid} has been removed from rpc-clients`);
            return { msg: `endpoint dropped from rpc...${JSON.stringify(config)}` }
        }, reply);
    });
    return this;
}

module.exports = plugin;